import axios from 'axios'
import { ElMessage } from 'element-plus'

// 创建全局单例实例
const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 30000
})

// 请求拦截
service.interceptors.request.use(
  (config: any) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers!['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  (error) => Promise.reject(error)
)

// 响应拦截
service.interceptors.response.use(
  (response: any) => {
    const res = response.data
    if (res.code === 200) {
      return res
    } else {
      ElMessage.error(res.msg || '操作失败')
      return Promise.reject(new Error(res.msg || 'Error'))
    }
  },
  (error) => {
    ElMessage.error(error.message || '服务器异常')
    return Promise.reject(error)
  }
)

// 封装请求方法
export const request = (options: any) => {
  return service(options)
}

export default request